package com.zrf.geekbang.spring.bean;

import com.zrf.geekbang.spring.bean.factory.DefaultUserFactory;
import com.zrf.geekbang.spring.bean.factory.UserFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ServiceLoader;

/**
 * 特殊bean定义
 *
 * @author zhouruifeng
 * @date 2020-06-21
 */
public class SpecialBeanInstantiationDemo {

    public static void main(String[] args) {
        //通过serviceLoader
        serviceLoader();
        //通过autowireCapableBeanFactory创建
        autowireCapableBeanFactory();
    }

    private static void autowireCapableBeanFactory() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "classpath:/META-INF/special-bean-instantiation-context.xml");
        AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
        UserFactory userFactory = autowireCapableBeanFactory.createBean(DefaultUserFactory.class);
        System.out.println(userFactory.createUser());

    }

    private static void serviceLoader() {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "classpath:/META-INF/special-bean-instantiation-context.xml");

        nativeServiceLoader();

        ServiceLoader<UserFactory> serviceLoader = applicationContext.getBean("userFactoryServiceLoader", ServiceLoader.class);
        soutServiceLoader(serviceLoader);
    }

    private static void soutServiceLoader(ServiceLoader<UserFactory> serviceLoader) {
        for (UserFactory userFactory : serviceLoader) {
            System.out.println(userFactory.createUser());
        }
    }

    public static void nativeServiceLoader() {
        ServiceLoader<UserFactory> serviceLoader = ServiceLoader.load(UserFactory.class, Thread.currentThread().getContextClassLoader());
        soutServiceLoader(serviceLoader);
    }
}
